package bar.dark.lee.common;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import bar.dark.lee.BDConstents;
import bar.dark.lee.R;
import bar.dark.lee.common.DBSQLite.ParseSelectData;

public class CalendarPickerActivity extends Activity implements OnClickListener, OnTouchListener {

	private ImageButton    pre,next;
	private Button okButton;
	private ArrayList<TextView> tempList = new ArrayList<TextView>();
	private ArrayList<TextView> list = new ArrayList<TextView>();
	
	private TextView    today,time;
	private TableLayout table;
	int     setYear;
	int     setMonth;
	int     setMonth2;
	int     setDay;
	
	private ArrayList<PositionClass> positionList = new ArrayList<PositionClass>();
	private String selectMonth = "";
	int tableLayoutWidth;
	int tableLayoutHeight;
	
	boolean firstRun = true;
	
	private ArrayList<String> dbData = new ArrayList<String>();
	
	int colorSelect;
	
	private DBSQLite sql;
	
	private int defaultPaintFlag;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
	    setContentView(R.layout.calendar_picker_activity);
	    
		sql = DBSQLite.getInstance(this);
		
		pre = (ImageButton) findViewById(R.id.calendar_picker_pre);
		next = (ImageButton) findViewById(R.id.calendar_picker_next);
		today = (TextView) findViewById(R.id.calendar_picker_today);
		time = (TextView) findViewById(R.id.calendar_picker_time);
		Calendar calendar = Calendar.getInstance();
		setYear = calendar.get(Calendar.YEAR);
		setMonth = calendar.get(Calendar.MONTH);
		setMonth2 = calendar.get(Calendar.MONTH) + 1;
		setDay = calendar.get(Calendar.DAY_OF_MONTH);
		time.setText("오늘은  " + setYear + "년  " + setMonth2 + "월  " + setDay
				+ "일 입니다.");
		
		table = (TableLayout) findViewById(R.id.calendar_picker_table);
		for (int i = 0; i < 6; i++) {
			TableRow tr = new TableRow(this);
			for (int j = 0; j < 7; j++) {
				BDTextView tv = new BDTextView(this);
				if (j == 0) {
					tv.setTextColor(Color.RED);
					tv.setTextSize(20);
				} else if (j == 6) {
					tv.setTextColor(Color.BLUE);
					tv.setTextSize(20);
				} else {
					tv.setTextColor(Color.BLACK);
					tv.setTextSize(20);
				}
				tv.setMinimumHeight(BDUtil.dipToPixel(this, 45));
				tv.setGravity(Gravity.CENTER);
				tr.addView(tv);
				tempList.add(tv);
				tv.setOnClickListener(this);
				//tv.setOnTouchListener(this);
				
			}
			table.addView(tr);
		}

		table.setStretchAllColumns(true);
		//table = (TableLayout) findViewById(R.id.week);
		//table.setOnTouchListener(this);
		findViewById(R.id.calendar_picker_frame).setOnTouchListener(this);
		View view = new View(this);
		view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		view.setOnTouchListener(this);
		((FrameLayout)findViewById(R.id.calendar_picker_frame)).addView(view);

		setCalendar(setYear, setMonth);

		pre.setOnClickListener(this);
		next.setOnClickListener(this);
		//okButton.setOnClickListener(this);
		
		colorSelect = getResources().getColor(R.color.selectCalendar);
		
		defaultPaintFlag = tempList.get(0).getPaintFlags();
	}
	
	private void setCalendar(int year, int month) 
	{
		if (list.size() > 0) 
		{
			for (int i = 0; i < list.size(); i++) 
			{
				list.get(i).setBackgroundColor(0);
				list.get(i).setPaintFlags(defaultPaintFlag);
			}
		}	
		
		list.clear();
		
		setSelectDayData(year, month);
		
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.YEAR, year);
		calendar.set(Calendar.MONTH, month);
		calendar.set(Calendar.DAY_OF_MONTH, 1);

		today.setText(year + "년 " + (month + 1) + "월");

		int getDay = calendar.get(Calendar.DAY_OF_WEEK);

		int j = 1;
		for (int i = 0; i < tempList.size(); i++) {
			tempList.get(i).setText("");
		}

		boolean flag = true;
		
		for (int i = getDay - 1; i < calendar
				.getActualMaximum(Calendar.DAY_OF_MONTH) + getDay - 1; i++) 
		{
			TextView temp = new TextView(this);
			temp = tempList.get(i);
			list.add(temp);
			for (int k=0; k<dbData.size(); k++) 
			{
				if (j == Integer.parseInt(dbData.get(k))) 
				{
					//temp.setHighlightColor(getResources().getColor(R.color.pink));
					temp.setPaintFlags(temp.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
					temp.setText(j + "");
					flag = false;
					break;
				}
			}
			
			if (flag) 
			{
				temp.setText(j + "");
			}
			
			flag = true;
			j++;
		}
		
		//checkBeforeSave();
		
		firstRun = true;
	}
	
	private void setSelectDayData(int year, int month)
	{
		dbData.clear();
		
		String query = "SELECT date FROM in_out";
		
		query = query + getDateForMonth(year, month);
		
		sql.selectMapTile(this, query + " ORDER BY date ASC;", new ParseSelectData() {
			
			@Override
			public void resultData(Cursor c) {
				int columnIndex = c.getColumnIndex("date");
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					dbData.add((c.getInt(columnIndex)+"").substring(6, 8));
					c.moveToNext();
				}
			}
		});
	}
	
//	/**
//	 * 이전에 저장해 놓은 내용을 불러온다.
//	 */
//	private void checkBeforeSave() 
//	{
//		selectDate.clear();
//		
//		for (int i=0; i<totalSelect.size(); i++) 
//		{
//			if (setMonth+1 == totalSelect.get(i).getMonth()) 
//			{
//				selectDate.addAll(totalSelect.get(i).getSelectDate());
////				for (int j=0; j<totalSelect.get(i).getSelectDate().size(); j++) {
////					selectDate.add(totalSelect.get(i).getSelectDate().get(j));
////				}
//			}
//		}
//		
//		for (int i=0; i<selectDate.size(); i++) {
//			list.get(Integer.parseInt(selectDate.get(i))-1).setBackgroundColor(colorSelect);
//		}
//	}
	
	private String getDateForMonth(int year, int month) 
	{
		String m = "" + (month+1);
		
		if (month+1 < 10) 
		{
			m = "0" + (m);
		}
		
		String date = year+"" + m;
		String query = " WHERE date >= " + (date+"01") + " and date <= " + (date+"31") + " ";
		return query;
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.calendar_picker_pre) 
		{
			//checkSelectedDate();
			//saveThisMonth();
			
			setMonth--;
			if (setMonth < 0) 
			{
				setYear--;
				setMonth = 11;
			}
			
			setCalendar(setYear, setMonth);
		} 
		else if (v.getId() == R.id.calendar_picker_next) 
		{
			
			//checkSelectedDate();
			//saveThisMonth();
			
			setMonth++;
			if (setMonth > 11) 
			{
				setMonth = 0;
				setYear++;
			}
			
			setCalendar(setYear, setMonth);
		} 
	}

private class PositionClass {
		
		private int left;
		private int top;
		private int right;
		private int bottom;
			
		public PositionClass(int left, int right, int top, int bottom) {
			this.left = left;
			this.top = top;
			this.right = right;
			this.bottom = bottom;
		}

		public int getLeft() {
			return left;
		}

		public void setLeft(int left) {
			this.left = left;
		}

		public int getTop() {
			return top;
		}

		public void setTop(int top) {
			this.top = top;
		}

		public int getRight() {
			return right;
		}

		public void setRight(int right) {
			this.right = right;
		}

		public int getBottom() {
			return bottom;
		}

		public void setBottom(int bottom) {
			this.bottom = bottom;
		}
	}

	int changedIndex = -1;

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		
		if (firstRun) 
		{
			positionList.clear();
			
			for (int i=0; i<list.size(); i++) 
			{
				TextView tv = list.get(i);
				
				if (!tv.getText().toString().equals("")) 
				{
					positionList.add(new PositionClass(tv.getLeft(), tv.getRight(), ((View)tv.getParent()).getTop(), ((View)tv.getParent()).getBottom()));
					//Log.e("111", tv.getText().toString()+","+tv.getLeft()+","+tv.getRight()+","+((View)tv.getParent()).getTop()+","+((View)tv.getParent()).getBottom());
				}
			}
			
			firstRun = false;
		}
		
		final int action = event.getAction();
		
		if (action == MotionEvent.ACTION_DOWN)
		{
			final float x = event.getX();
	        final float y = event.getY();
	        
	        String selectDate = "";
	        
			for (int i=0; i<positionList.size(); i++) 
	        {
	        	if (changedIndex == i) 
	        	{
	        		continue;
	        	}
	        	
	        	PositionClass position = positionList.get(i);
	        	
	        	if (position.getLeft() < x && x < position.getRight() && position.getTop() < y && y <position.getBottom()) {
	        		
	        		//Log.e("123", (i+10)+","+position.getLeft()+","+position.getRight()+","+position.getTop()+","+position.getBottom()+",");
		        	
	        		changedIndex = i;
	        		
	        		TextView view = list.get(i);
					view.buildDrawingCache();
					Bitmap bitmap = view.getDrawingCache();
					int color = bitmap.getPixel(0, 0);
					//Log.e("ChecktedText","Background Color: " + color);
					view.destroyDrawingCache();
					
	        		if (color == 0)
	        		{
	        			list.get(i).setBackgroundColor(colorSelect);
	        		}
	        		
	        		selectDate = list.get(i).getText().toString();
	        	}
	        }
			
			Intent intent = new Intent();
			String year = setYear + "";
			String month = "";
			String date = "";
			
//			Log.e("123123", (setYear + "") + ((setMonth+1) + "") + date);
			if ((setMonth+1) < 10)
			{
				month = "0" + (setMonth+1);
			}
			else
			{
				month = (setMonth+1) + "";
			}
			
			if (Integer.parseInt(selectDate) < 10)
			{
				date = "0" + selectDate;
			}
			else
			{
				date = selectDate;
			}
			
			intent.putExtra(BDConstents.REQUEST_CALENDAR_PICKER_STRING, year + month + date);
			setResult(Activity.RESULT_OK, intent);
			finish();
	    }

		return true;
	}
}
